<script name="DraggableImageUpload" setup>
import { uploadUrl } from '@/utils/request'// 请求url
import { getToken } from '@/utils/auth'
import { Check, Delete, Plus, ZoomIn } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import { computed, onMounted, reactive, ref } from 'vue';
import { VueDraggable } from 'vue-draggable-plus';

const draggableRef = ref()

const props = defineProps({
  // 接受上传的文件类型（thumbnail-mode 模式下此参数无效）
  accept: {
    type: String,
    default: '.jpg,.jpeg,.png'
  },
  // 允许上传文件的最大数量
  limit: {
    type: Number,
    default: 9999
  },
  // 是否支持多选文件
  multiple: {
    type: Boolean,
    default: true
  },
  // 是否自动上传文件
  autoUpload: {
    type: Boolean,
    default: false
  },
  modelValue: {
    type: Array,
    default: () => []
  },
  uploadData: {
    type: Object,
    default: () => {}
  }
});

const token = ref();
onMounted(() => {
  token.value = getToken();
})

const emit = defineEmits(['update:modelValue']);
const curList = computed({
  get () {
    return props.modelValue
  },
  set (newValue) {
    emit('update:modelValue', newValue);
  }
});

// 元素开始拖拽
const onStart = () => {
  console.log('start')
}

// 元素顺序更新时触发
const onUpdate = () => {
  console.log(curList.value, 'update++++++++++++++')
}

// 图片预览
const handleImgPreview = (domClass, index) => {
  /*   showViewer.value = true
    previewList.value = [url] */
  const dom = document.getElementsByClassName(domClass);
  dom[index].firstElementChild.click(); // 调用 el-image 的预览方法
}

// 删除图片
const onImageRemove = (url) => {
  let list = JSON.parse(JSON.stringify(curList.value))
  list.forEach((item, index) => {
    if (url === item.url) {
      list.splice(index, 1)
    }
  })
  curList.value = list
}

// 上传前校验
const beforeImgUpload = rawFile => {
  let types = ['image/jpeg', 'image/jpg', 'image/png'];
  const size = rawFile.size
  const isImage = types.includes(rawFile.type);
  const isLt5M = size / 1024 / 1024 < 5
  if (!isImage) {
    ElMessage('请上传jpeg、jpg、png类型的图片', {
      type: 'error'
    });
    return false;
  } else if (!isLt5M) {
    ElMessage('上传图片大小不能超过5MB', {
      type: 'error'
    });
    return false
  }
  return true;
};

// 上传成功,给图片加前缀，防止切换时图片不显示
function handleImgSuccess () {
  curList.value.forEach(item => {
    item.url = item.response ? item.response.data.url : item.url
  });
  console.log('curList', curList.value)
}

</script>

<template>
  <div class="draggable_image_upload">
    <VueDraggable
      ref="draggableRef"
      v-model="curList"
      class="box-uploader"
      :animation="600"
      easing="ease-out"
      ghost-class="ghost"
      draggable="ul"
      @start="onStart"
      @update="onUpdate"
    >
      <!-- 使用element-ui el-upload自带样式 -->
      <ul v-for="(item, index) in curList" :key="index" class="el-upload-list el-upload-list--picture-card">
        <li class="el-upload-list__item is-success animated">
          <el-image class="originalImg" fit="contain" :src="item.url" :preview-src-list="[item.url]" />
          <!--  <el-icon>
            <Close />
          </el-icon> -->
          <label class="el-upload-list__item-status-label">
            <el-icon class="el-icon--upload-success el-icon--check">
              <Check />
            </el-icon>
          </label>
          <span class="el-upload-list__item-actions">
            <!-- 预览    -->
            <span class="el-upload-list__item-preview" @click="handleImgPreview('originalImg', index)">
              <el-icon>
                <ZoomIn />
              </el-icon>
            </span>
            <!-- 删除    -->
            <span class="el-upload-list__item-delete" @click="onImageRemove(item.url)">
              <el-icon>
                <Delete />
              </el-icon>
            </span>
          </span>
        </li>
      </ul>
      <!-- 上传组件 -->
      <el-upload
        v-if="curList.length < limit"
        v-model:file-list="curList"
        :action="uploadUrl"
        :multiple="multiple"
        list-type="picture-card"
        :accept="accept"
        :show-file-list="false"
        :before-upload="beforeImgUpload"
        :on-success="handleImgSuccess"
        :data="uploadData"
        :headers="{
          'authorization-business': token
        }"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>
    </VueDraggable>
  </div>
</template>

<style scoped lang="scss">
.box-uploader{
  display: flex;
  flex-wrap: wrap;
  .el-upload-list__item{
    display: flex;
    justify-content: center;
  }
}
</style>